package com.company.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.common.JwtUtils;
import com.company.common.R;
import com.company.entity.Address;
import com.company.entity.Users;
import com.company.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@RestController
public class LoginController {
    @Resource
    UsersService usersService;

    /*
    * 管理员登录
    * */
    @CrossOrigin(origins = "*")
    @PostMapping("/Login")
    public R Login(@RequestBody Users users){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.setEntity(users);
        Users one = this.usersService.getOne(queryWrapper);
        if (one == null){
            return new R().setCode(502).setMessage("用户名密码错误");
        }else{
            HashMap<String,Object> hashMap=new HashMap<>();
            hashMap.put("id",one.getId());
            hashMap.put("username",one.getUsername());
            hashMap.put("password",one.getPassword());
            String jwtToken= JwtUtils.createJwtToken(hashMap);
            return new R().add("jwtToken",jwtToken);
        }
    }

    /*
    * 管理员信息查询
    * */
    @CrossOrigin(origins = "*")
    @RequestMapping("/selectUser2")
    public R selectUser2(){
        List<Users> list = this.usersService.list();
        return new R().add("list",list);
    }

    /*
     *管理员密码修改修改
     * */
    @PostMapping("/updateUser")
    public R UpdateAddress(@RequestBody Users users){
        R r = new R();
        boolean b = this.usersService.updateById(users);
        if (!b){
            r.setCode(100);
        }
        return r;
    }

    /*
     * 根据id查询管理员信息
     * */
    @CrossOrigin(origins = "*")
    @PostMapping("/selectUserbyid")
    public R selectUserbyid(@RequestBody Users users){
        Users byId = this.usersService.getById(users.getId());
        return new R().add("byId",byId);
    }

    /*
    * 添加管理员信息
    * */
    @PostMapping("/InsertUser")
    public R InsertUser(@RequestBody Users users){
        this.usersService.save(users);
        return new R();
    }

    /*
    * 删除管理员信息
    * */
    @RequestMapping("/delUser/{id}")
    public R delUser(@PathVariable("id") int id){
        boolean remove = this.usersService.removeById(id);
        R r=new R();
        if(remove==true){
            r.setMessage("删除成功");
        }else{
            r.setMessage("删除失败");
        }
        return r;
    }

}
